//
//  EMSelectItemViewController.swift
//  Hyphenate-Demo-Swift
//
//  Created by 杜洁鹏 on 2017/11/29.
//  Copyright © 2017年 杜洁鹏. All rights reserved.
//

import UIKit
import Hyphenate

//import Toast_Swift

protocol SelectMemberItemViewControllerDelegate {
    func didSelected()
}

class InviteGroupListController: EMSelectItemViewController {
    var groups: [String: String] = [:]
    func showGroupList(){
        var contactList = [String]()
        EMClient.shared().groupManager.getJoinedGroupsFromServer(withPage: 1, pageSize: 99) { (groupList, error) in
          
            if error == nil && groupList != nil {
               
                for group in groupList as! Array<EMGroup> {
                    let model = EMGroupModel.createWith(conference: group)
                    contactList.append(model.subject! )
                    self.groups.updateValue(model.subject!, forKey: model.id!)
                }
                
                
                self.reloadData(contactList:contactList)
            }
        }

        
   
    }
    
    override func updateSelectedCount() {
        
    }
    
    func reloadData(contactList: Array<String>){
        sortContacts(contactList: contactList)
        weak var weakSelf = self
        DispatchQueue.main.async {
            weakSelf?.tableView.reloadData()
            weakSelf?.refreshControl?.endRefreshing()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Choose Group".localized()
        tableView.setEditing(false , animated: false)
       
    }
    override func setupDataSource() {
            showGroupList()
    }
    
    
    override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
      
    }

  
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var model: EMUserModel?
        
        model = (contacts[indexPath.section] as! Array)[indexPath.row]
       
        for (v, k) in groups {
            if(model?.hyphenateID == k){
    
                let inviteGroupMemberListController = InviteGroupMemberListController()
                inviteGroupMemberListController.delegate = delegate
                inviteGroupMemberListController.groupId = v;
                let nav = UINavigationController.init(rootViewController: inviteGroupMemberListController)
                self.present(nav, animated: true, completion: nil)
            }
        }
      
    }
    
}
